package net.huashitong.user.web;

import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.ObjectUtils;
import net.huashitong.Indicators.entity.LoginLog;
import net.huashitong.Indicators.entity.UserInfo;
import net.huashitong.Indicators.filter.UserInfoFilter;
import net.huashitong.Indicators.service.GetDataService;
import net.huashitong.Indicators.service.LoginLogService;
import net.huashitong.Indicators.service.SmsProcess;
import net.huashitong.Indicators.service.UserInfoService;
import net.huashitong.Indicators.utils.DateForIndUtils;
import net.huashitong.Indicators.utils.TokenUtil;
import net.huashitong.appsecurity.AESUtil;
import net.huashitong.appsecurity.MD5;
import net.huashitong.until.Until;
import net.huashitong.user.filter.LoginFilter;
import net.huashitong.user.service.UserAuthService;
import net.huashitong.user.service.UserService;
import net.huashitong.user.utils.RegularExpressionsUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.StringUtils;


/**
 * 用户模块接口
 *
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.09.04
 */
@Controller
@RequestMapping("/app/user")
public class UserController extends JsonBaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UserAuthService authService;
    @Autowired
    private GetDataService getDataService;
    @Autowired
    private LoginLogService loginLogService;

    Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserController(UserService userService, SysUserService sysUserService) {
        this.userService = userService;
        this.sysUserService = sysUserService;
    }

    @Override
    protected String getView(String s) {
        return null;
    }


    /**
     * 登录之前，判断是否需要手势校验
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "preloginvalidate", method = RequestMethod.POST)
    public Message preLoginValidate(@RequestBody UserInfoFilter filter) {
        return coverMessage("200", "校验成功");
    }

    /**
     * 加密
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/secret", method = RequestMethod.POST)
    public Message secret(@RequestBody LoginFilter filter) throws Exception {
        //通过参数解密   32位加密，其中16位
        String key = MD5.encrypt(filter.getTimestamp() + filter.getRandom());    //秘钥
        String iv = MD5.encrypt(key);                                                //iv
        String cSrc = "{\n" +
                "\"user\":\"15160030509\",\n" +
                "\"pwd\":\"123456\"\n" +
                "}";
        String secretText = AESUtil.getInstance().encrypt(cSrc, "utf-8", key, iv);
        System.out.println("密文：" + secretText);
        //MD5 32位加密-->密签
        String resultSecret = MD5.md5(filter.getTimestamp() + filter.getRandom() + secretText).toUpperCase();
        System.out.println("密签：" + resultSecret);
        return coverMessage("200", "获取成功");
    }

    /**
     * 登录
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Message login(@RequestBody LoginFilter filter) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        //通过参数解密   32位加密，其中16位
        String key = MD5.encrypt(filter.getTimestamp() + filter.getRandom());    //秘钥
        String iv = MD5.encrypt(key);                                                 //iv
        //解密得到明文（账号密码）(SecretNum:密文)
        String clearText = AESUtil.getInstance().decrypt(filter.getSecretNum(), "utf-8", key, iv);
        //MD5 32位加密-->密签
        String resultSecret = MD5.md5(filter.getTimestamp() + filter.getRandom() + filter.getSecretNum()).toUpperCase();
        //校验密签
        if (resultSecret.equals(filter.getSecretSign())) {
            //通过明文获取用户名与密码
            JSONObject jsStr = JSONObject.parseObject(clearText);
            String tel = jsStr.getString("user");
            String pwd = jsStr.getString("pwd");
            String equipCode = jsStr.getString("equipCode");    //获取设备编码
            JSONObject jsonObject = null;
            //判断用户名跟密码不能为空
            if (StringUtils.isNotBlank(tel)) {
                if (StringUtils.isNotBlank(pwd)) {

//                    //需要调用接口（需要token）
//                    UserInfo userInfo = userInfoService.getUserInfoByTel(tel);
//                    String userId = userInfo.getUserId();
//                    String url = "user=" + userId + "&pwd=" + pwd;
//                    String resStr = Until.HttpGET(Until.GET_TOKEN_LOGIN + url, 5000, 5000);
//                    //得到json对象
//                    jsonObject = JSONObject.parseObject(resStr);
//                    if ("200".equals(jsonObject.getString("returncode"))) {//请求成功:returncode==200
//                        String token = jsonObject.getString("returndata");  //得到token
//                        //如果登录成功，保存账号密码以及token、本地token、生成时间
//                        UserInfo userInfo = userInfoService.getUserInfoByTel(tel);
//                        String localToken = new TokenUtil().makeToken() ;
//                        String time = new DateForIndUtils().getCurDate("yyyy-MM-dd HH:mm:ss");
//                        userInfo.setTokenTime(time);
//                        userInfo.setLocalTokenTime(time);
//                        userInfo.setLocalToken(localToken);
//                        userInfo.setPwd(pwd);
//                        userInfo.setToken(token);
//                        //更新密码跟token
//                        userInfoService.update(userInfo);
//                        map.put("localToken",localToken);               //本地token
//                        map.put("token",token);                         //第三方token
//                        map.put("userName", userInfo.getUserName());    //用户名
//                        map.put("shoushi", "");                         //手势
//                        map.put("noRight", userInfo.getNoRight());      //指标
//                        map.put("openId",userInfo.getSysId());          //用户ID
//                        //用户角色
//                        map.put("roles",userInfo.getRoles());
//                        return coverMessage("200", "登录成功", map);
//                    } else {
//                        return coverMessage("500", "登录失败");
//                    }

                    //不用调用接口（不需要token）
                    //如果登录成功，保存账号密码以及token
                    UserInfo userInfo = new UserInfo();
                    UserInfo userInfo1 = userInfoService.getUserInfoByTel(tel);
                    UserInfo userInfo2 = userInfoService.getUserInfoByUserId(tel);
                    if (userInfo1 == null && userInfo2 ==null) {
                        return coverMessage("500", "用户不存在");
                    }else{
                        if(ObjectUtils.isNotBlank(userInfo1)){
                            userInfo = userInfo1;
                        }else{
                            userInfo = userInfo2;
                        }
                    }

                    //接口验证用户
                    boolean ifLogin = userInfoService.checkLogin(userInfo.getUserId(),pwd);
                    if(ifLogin){
                        //是否需要手势验证  编码code
                        String code = authService.getCodeValid(userInfo,equipCode);
                        //设备编码改变需要
                        userInfo.setEquipCode(equipCode);   //保存设备编码
                        String localToken = new TokenUtil().makeToken();
                        String time = new DateForIndUtils().getCurDate("yyyyMMdd HH:mm:ss");
                        userInfo.setTokenTime(time);
                        userInfo.setLocalTokenTime(time);
                        userInfo.setLocalToken(localToken);
                        userInfo.setPwd(pwd);
                        userInfoService.update(userInfo);
                        map.put("userName", userInfo.getUserName());
                        map.put("localToken", localToken);
                        //指标
                        map.put("openId", userInfo.getSysId());          //用户ID
                        map.put("shoushi",userInfo.getSsPwd());            //手势密码
                        map.put("noRight", userInfo.getNoRight());
                        //用户角色
                        map.put("roles", userInfo.getRoles());

                        //记录登录日志
                        LoginLog loginLog = new LoginLog();
                        loginLog.setTel(userInfo.getTel());
                        loginLog.setUserId(userInfo.getUserId());
                        loginLog.setUserName(userInfo.getUserName());
                        loginLog.setUserSysId(userInfo.getSysId());
                        loginLogService.save(loginLog);

                        return coverMessage(code, "登陆成功", map);
                    }else{
                        return coverMessage("500", "登陆失败，账号或者密码错误");
                    }

                } else {
                    return coverMessage("500", "密码不能为空");
                }
            }
            return coverMessage("500", "用户名不能为空");
        } else {
            return coverMessage("500", "获取失败");
        }
    }

    /**
     * 发送验证码
     *
     * @param filter tel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendValidCode", method = RequestMethod.POST)
    public Message sendValidCode(@RequestBody UserInfoFilter filter) {
        //—————————————————————————此处需加手机号码限制过滤————————————————————————————————
        Map<String, Object> map;
        String tel = "";
        if (StringUtils.isBlank(filter.getTel())
                || !RegularExpressionsUtils.phone(filter.getTel())) {
            //根据用户userId获取用户手机号码
            UserInfo userInfo2 = userInfoService.getUserInfoByUserId(filter.getTel());
            if(ObjectUtils.isBlank(userInfo2)){
                return coverMessage("201", "该用户没有设置手机号");
            }
            if (StringUtils.isBlank(userInfo2.getTel())
                    || !RegularExpressionsUtils.phone(userInfo2.getTel())){
                return coverMessage("201", "内部出错");
            }else{
                tel = userInfo2.getTel();
            }
        }else{
            tel = filter.getTel();
        }
        String url = "phone=" + tel;
        //去掉预制用户拦截
        /*String judgeUser = null;
        try {
            judgeUser = Until.HttpGET(Until.JUDGE_USER + url, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口："+ Until.JUDGE_USER + url);
        }
        JSONObject jsonb = JSONObject.parseObject(judgeUser);
        if (!"200".equals(jsonb.getString("returncode"))) {
            return coverMessage("201", "该用户不是预制用户");
        }
        if("200".equals(jsonb.getString("returncode"))){
            if("false".equals(jsonb.getString("returndata"))){
                return coverMessage("201", "该用户不是预制用户");
            }
        }*/
        String validCode = Integer.toString((int) ((Math.random() * 9 + 1) * 10000));
        String smsContent = null;
        //action------1:注册|2:忘记密码|3:修改密码|4:重置密码|5:激活用户
        if ("1".equals(filter.getAction())) {
            smsContent = "验证码：" + validCode + "，您正在进行注册用户操作，2分钟内有效，请勿泄露--厦门数据";
        } else if ("2".equals(filter.getAction())) {
            smsContent = "验证码：" + validCode + "，您正在进行忘记密码操作，2分钟内有效，请勿泄露--厦门数据";
        } else if ("3".equals(filter.getAction())) {
            smsContent = "验证码：" + validCode + "，您正在进行修改密码操作，2分钟内有效，请勿泄露--厦门数据";
        }
//        String smsContent = "您的验证码是" + validCode + "。如非本人操作，请忽略本短信--厦门数据";
        SmsProcess sms = new SmsProcess();
        log.info("内容：  " + smsContent);
        log.info("电话：  " + tel);
        log.info("标识符：" + filter.getAction());
        map = sms.SendMts(tel, smsContent);
//        map.put("validCode",validCode);
        userService.saveValid(tel, validCode);
        if ("0".equals(map.get("StateCode"))) {
            return coverMessage("200", "短信验证码发送成功");
        } else {
            return coverMessage(map.get("StateCode").toString(), "短信验证码发送失败");
        }

    }


    /**
     * 模拟发送验证码
     *
     * @param filter tel
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "/sendValidCode", method = RequestMethod.POST)
//    public Message sendValidCode(@RequestBody UserInfoFilter filter) {
//        //—————————————————————————此处需加手机号码限制过滤————————————————————————————————
//
//        if (StringUtils.isBlank(filter.getTel())
//                || !RegularExpressionsUtils.phone(filter.getTel())) {
//            return coverMessage("500", "参数有误，请重新输入");
//        }
//
//        String url = "phone=" + filter.getTel();
//        String judgeUser = Until.HttpGET(Until.JUDGE_USER + url, 5000, 5000);
//        JSONObject jsonb = JSONObject.parseObject(judgeUser);
//        if (!"200".equals(jsonb.getString("returncode"))) {
//            return coverMessage("500", "该用户不是预制用户");
//        }else if("200".equals(jsonb.getString("returncode"))){
//            if("false".equals(jsonb.getString("returndata"))){
//                return coverMessage("500", "该用户不是预制用户");
//            }
//        }
//
//        String validCode = Integer.toString((int) ((Math.random() * 9 + 1) * 10000));
//        String smsContent = null;
//        //action------1:注册|2:忘记密码|3:修改密码
//        if ("1".equals(filter.getAction())) {
//            smsContent = "验证码：" + validCode + "，您正在进行注册用户操作，2分钟内有效，请勿泄露--厦门数据";
//        } else if ("2".equals(filter.getAction())) {
//            smsContent = "验证码：" + validCode + "，您正在进行忘记密码操作，2分钟内有效，请勿泄露--厦门数据";
//        } else if ("3".equals(filter.getAction())) {
//            smsContent = "验证码：" + validCode + "，您正在进行修改密码操作，2分钟内有效，请勿泄露--厦门数据";
//        }
//        SmsProcess sms = new SmsProcess();
//        log.info("内容：  " + smsContent);
//        log.info("电话：  " + filter.getTel());
//        log.info("标识符：" + filter.getAction());
//        userService.saveValid(filter.getTel(), validCode);
//        Map<String, Object> map = new HashMap<>();
//        map.put("validCode",validCode);
//        map.put("smsContent",smsContent);
//        map.put("action",filter.getAction());
//        map.put("tel",filter.getTel());
//        return coverMessage("200", "短信验证码发送成功",map);
//    }

    /**
     *
     * @param filter tel/validCode/passWord/newPassWord
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editpwd", method = RequestMethod.POST)
    public Message editPwd(@RequestBody UserInfoFilter filter) {
        String tel = "";
        if (StringUtils.isBlank(filter.getTel())
                || !RegularExpressionsUtils.phone(filter.getTel())) {
            //根据用户userId获取用户手机号码
            UserInfo userInfo2 = userInfoService.getUserInfoByUserId(filter.getTel());
            if(ObjectUtils.isBlank(userInfo2)){
                return coverMessage("201", "该用户没有设置手机号");
            }
            if (StringUtils.isBlank(userInfo2.getTel())
                    || !RegularExpressionsUtils.phone(userInfo2.getTel())){
                return coverMessage("201", "内部出错");
            }else{
                tel = userInfo2.getTel();
            }
        }else{
            tel = filter.getTel();
        }
        //判断手机验证码
        boolean isOk = authService.telValidateCode(tel, filter.getValidCode());
//        boolean isOk = true;
        if (isOk) {
            //修改密码、忘记密码（重置密码）
            UserInfo userinfo = userInfoService.getUserInfoByTel(tel);
            if (userinfo != null) {
                if(authService.chongzhi(tel,filter.getNewPassWord())){
                    String pwd = filter.getNewPassWord();
                    userinfo.setPwd(MD5.md5(pwd));
                    userInfoService.update(userinfo);
                    Map<String, Object> map = new HashMap<>();
                    map.put("tel", tel);
                    map.put("newPassWord", filter.getNewPassWord());
                    map.put("validate", filter.getValidCode());
                    log.info("本地修改密码成功");
                    return coverMessage("200", "修改密码成功", map);
                }else{
                    log.info("密码修改失败");
                    return coverMessage("201", "密码修改失败");
                }

            } else {
                log.info("用户不存在");
                return coverMessage("201", "用户不存在");
            }
        } else {
            log.info("验证码不合法");
            return coverMessage("201", "验证码错误");
        }
    }

    /**
     * 注册用户
     * tel、validCode、passWord、userId
     * @param filter UserInfo filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/registeruser", method = RequestMethod.POST)
    public Message registerUser(@RequestBody UserInfoFilter filter) {
        String tel = filter.getTel();
        String validCode = filter.getValidCode();
        String passWord = filter.getPassWord();
        String userId = tel/*getUUID().substring(0,9)*/;
        //判断手机验证码
        boolean isOk = authService.telValidateCode(tel, validCode);
//        boolean isOk = true;
        if(isOk){
            Map<String,String> resMap = authService.jihuo(tel,passWord,userId);

//            //激活写死
//            Map<String,String> resMap = new HashMap<>();
//            resMap.put("returncode","200");

            if("200".equals(resMap.get("returncode"))){
                if(authService.registerUserToLocal(tel,passWord,userId)){
                    UserInfo userInfo = userInfoService.getUserInfoByTel(tel);
                    Map<String,String> map = new HashMap<>();
                    map.put("openId",userInfo.getSysId());
                    return coverMessage("200", "注册成功",map);
                }else{
                    return coverMessage("505", "注册失败");
                }
            }else if("504".equals(resMap.get("returncode"))){
                if(authService.registerUserToLocal(tel,passWord,userId)){
                    UserInfo userInfo = userInfoService.getUserInfoByTel(tel);
                    Map<String,String> map = new HashMap<>();
                    map.put("openId",userInfo.getSysId());
                    return coverMessage("200", "注册成功",map);
                }else{
                    return coverMessage("505", "注册失败");
                }
            }else{
                log.info(resMap.get("returndata"));
                return coverMessage("505", resMap.get("returndata"));
            }
        }else{
            log.info("手机验证码错误");
            return coverMessage("505", "手机验证码错误");
        }
    }

    /**
     * 手动执行更新脚本
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDataxxx", method = RequestMethod.GET)
    public Message getDataxxx() {
        getDataService.timeclock();
        return coverMessage("200", "更新数据成功");
    }
}
